from datetime import datetime
from typing import Dict, Any
from dataclasses import asdict

from .models import TableDefinition, SQLParseResult

def get_current_timestamp() -> str:
    """获取当前时间戳，格式为ISO 8601"""
    return datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")

class SQLOutputFormatter:
    """SQL输出格式化器"""

    def format_result(self, table: TableDefinition) -> Dict[str, Any]:
        """格式化解析结果

        Args:
            table: 表定义对象

        Returns:
            格式化后的字典结果
        """
        # 创建解析结果对象
        result = SQLParseResult(
            version="1.0",
            metadata=self._build_metadata(table),
            table=self._build_table_dict(table),
            columns=self._build_columns_dict(table)
        )

        # 转换为字典
        return asdict(result)

    def _build_metadata(self, table: TableDefinition) -> Dict[str, str]:
        """构建元数据

        Args:
            table: 表定义对象

        Returns:
            元数据字典
        """
        return {
            "source_file": f"{table.name}.sql",  # 使用表名作为源文件名
            "dialect": "mysql",
            "timestamp": get_current_timestamp()
        }

    def _build_table_dict(self, table: TableDefinition) -> Dict[str, Any]:
        """构建表信息字典

        Args:
            table: 表定义对象

        Returns:
            表信息字典
        """
        return {
            "name": table.name,
            "comment": table.comment,
            "engine": table.options.get("engine"),
            "charset": table.options.get("charset"),
            "collate": table.options.get("collate"),
            "indexes": [asdict(idx) for idx in table.indexes]
        }

    def _build_columns_dict(self, table: TableDefinition) -> Dict[str, Dict]:
        """构建列信息字典

        Args:
            table: 表定义对象

        Returns:
            列信息字典
        """
        columns_dict = {}
        for col in table.columns:
            columns_dict[col.name] = {
                "name": col.name,
                "type": {
                    "name": col.type["type"],
                    "length": col.type.get("length")
                },
                "nullable": col.nullable,
                "auto_increment": col.auto_increment,
                "comment": col.comment,
                "default_value": col.default_value,
                "primary_key": col.primary_key
            }
        return columns_dict